package com.xc.quickstart.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.xc.quickstart.common.annotation.SsoAuthority;
import com.xc.quickstart.common.context.ApiContext;
import com.xc.quickstart.common.model.ApiResponse;
import com.xc.quickstart.manager.sso.SsoManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author : pdl
 * @date : 2021/3/23 20:23
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SsoManager ssoManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!judge(handler)) {
            return true;
        }

        if (!checkRoleAuth()) {
            returnFail(response, ApiResponse.fail("无操作权限，请联系管理员"));
            return false;
        }

        Method method = ((HandlerMethod) handler).getMethod();

        if (method.getAnnotation(SsoAuthority.class) == null) {
            return true;
        }

        Annotation[] annotations = method.getAnnotations();
        String path = "";
        if (annotations.length > 0) {
            for (Annotation annotation : annotations) {
                Class<? extends Annotation> clazz = annotation.annotationType();
                if (clazz == PostMapping.class) {
                    path = ((PostMapping) annotation).path()[0];
                } else if (clazz == GetMapping.class) {
                    path = ((GetMapping) annotation).path()[0];
                } else if (clazz == RequestMapping.class) {
                    path = ((RequestMapping) annotation).path()[0];
                }
            }
        }
        log.info("request url = {}", path);
        boolean r = checkAuth(path);
        if (!r) {
            returnFail(response, ApiResponse.fail("接口未授权，请联系管理员"));
        }
        return r;
    }

    private void returnFail(HttpServletResponse response, ApiResponse res) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.getWriter().print(JSON.toJSONString(res));
    }

    private boolean checkRoleAuth() {
        Integer userId = ApiContext.getApiContextModel().getUserId();
        return ssoManager.checkRoleAuth(userId);
    }

    private boolean checkAuth(String url) {
        Integer userId = ApiContext.getApiContextModel().getUserId();
        return ssoManager.checkAuthority(userId, url);
    }

    private boolean judge(Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }

        Method method = ((HandlerMethod) handler).getMethod();
        Class<?> declaringClass = method.getDeclaringClass();

        SsoAuthority annotation = method.getAnnotation(SsoAuthority.class);
        if (Objects.isNull(annotation)) {
            annotation = declaringClass.getAnnotation(SsoAuthority.class);
        }

        if (Objects.nonNull(annotation)) {
            return true;
        }

        return false;
    }
}
